package cn.gdust.servlet;

import cn.gdust.dao.BarrageDao;
import cn.gdust.entity.Barrage;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/AddBarrageServlet.do")
public class AddBarrageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            request.setCharacterEncoding("UTF-8");
            // 从请求体中获取JSON数据
            String json = request.getReader().lines().reduce("", (accumulator, actual) -> accumulator + actual);

            // 使用Gson将JSON数据转换为Barrage对象
            Gson gson = new Gson();
            Barrage barrage = gson.fromJson(json, Barrage.class);

            BarrageDao barrageDao = new BarrageDao();
            String count = String.valueOf(barrageDao.addBarrage(barrage));
            response.getWriter().write(count);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
